package com.xuecheng.service.impl;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.xuecheng.model.dto.CheckCodeParamsDTO;
import com.xuecheng.model.vo.CheckCodeResultVO;
import com.xuecheng.service.AbstractCheckCodeService;
import com.xuecheng.service.CheckCodeService;
import com.xuecheng.utils.EncryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Base64Encoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 图片验证码生成器
 */
@Slf4j
@Service("PicCheckCodeService")
public class PicCheckCodeServiceImpl extends AbstractCheckCodeService implements CheckCodeService {
	
	@Resource
	private DefaultKaptcha kaptcha;
	
	@Resource(name = "NumberLetterCheckCodeGenerator")
	@Override
	public void setCheckCodeGenerator(CheckCodeGenerator checkCodeGenerator) {
		this.checkCodeGenerator = checkCodeGenerator;
	}
	
	@Resource(name = "UUIDKeyGenerator")
	@Override
	public void setKeyGenerator(KeyGenerator keyGenerator) {
		this.keyGenerator = keyGenerator;
	}
	
	
	@Resource(name = "MemoryCheckCodeStore")
	@Override
	public void setCheckCodeStore(CheckCodeStore checkCodeStore) {
		this.checkCodeStore = checkCodeStore;
	}
	
	
	@Override
	public CheckCodeResultVO generate(CheckCodeParamsDTO checkCodeParamsDTO) {
		GenerateResult generate = generate(checkCodeParamsDTO, 4, "checkcode:", 60);
		return CheckCodeResultVO.builder().aliasing(createPic(generate.getCode())).key(generate.getKey()).build();
		
	}
	
	private String createPic(String code) {
		// 生成图片验证码
		ByteArrayOutputStream outputStream = null;
		BufferedImage image = kaptcha.createImage(code);
		
		outputStream = new ByteArrayOutputStream();
		String imgBase64Encoder = null;
		try {
			// 对字节数组Base64编码
			Base64Encoder base64Encoder = new Base64Encoder();
			ImageIO.write(image, "png", outputStream);
			imgBase64Encoder = "data:image/png;base64," + EncryptUtil.encodeBase64(outputStream.toByteArray());
		} catch (IOException e) {
			log.error("图片验证码生成失败:{}", e.getMessage());
		} finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				log.error("图片验证码生成失败:{}", e.getMessage());
			}
		}
		return imgBase64Encoder;
	}
}
